package com.xyz.rok.tools.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xyz.rok.tools.constant.SystemCode;
import com.xyz.rok.tools.model.Result;
import com.xyz.rok.tools.utils.JwtUtil;
import com.xyz.rok.tools.utils.TokenPayload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author ZhangYiXin
 * @version 1.0
 * @date 2021/7/1 17:47
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            responseError(response);
            return false;
        }
        TokenPayload tokenPayload = jwtUtil.verifierToken(request.getRequestURI(), token);
        if (tokenPayload == null) {
            responseError(response);
            return false;
        }
        if (tokenPayload.getUserId() != null) {
            request.setAttribute("userId", tokenPayload.getUserId());
        }

        if (tokenPayload.getUnionIds() != null) {
            request.setAttribute("unionIds", tokenPayload.getUnionIds());
        }
        return true;
    }

    private void responseError(HttpServletResponse response) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        writer.write(mapper.writeValueAsString(Result.error(SystemCode.SYS_NO_LOGIN.getCode(), SystemCode.SYS_NO_LOGIN.getMessage())));
    }
}
